import { DELETE_AUTHORITY_INFO, UPDATE_AUTHORITY_PARAMS } from './types'
import { postLoginApi } from '@/api/auth'
import { Ls } from '@/utils/common'

const actions = {
  // 将用户信息与本地存储同步
  saveStateToStorageAction: ({ commit, dispatch, state }) => {
    // localStorage.setItem('authority_userinfo', JSON.stringify(state))
    Ls.put('authority_userinfo', state)
  },
  deleteStateInStorageAction: ({ commit, dispatch, state }) => {
    Ls.del('authority_userinfo')
    commit({ type: DELETE_AUTHORITY_INFO })
  },
  // 从本地取出用户信息更新vuex
  updateStateByStorageAction: ({ commit }) => {
    const [, state] = Ls.get('authority_userinfo')
    state && commit({ type: UPDATE_AUTHORITY_PARAMS, ...state })
    // statte返回出去, 如果有值,说明已经登录过了, 需要注意, 及时action中, 没有异步动作, 也会转化成promise
    return state
  },
  loginPostAction: async ({ commit, dispatch }, payload) => {
    try {
      const result = await postLoginApi(payload)
      commit({ type: UPDATE_AUTHORITY_PARAMS, ...result })
      // 因为考虑到操作本地存储的动作最终还是为了store来服务,也是与state相关的动作,应该从视图中剥离
      dispatch({ type: 'saveStateToStorageAction' })
      return true
    } catch (error) {
      console.log('error', error)
      return false
    }
  }
}

export default actions
